package com.apes.fn.scm.used.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.scm.income.model.MoneyIncome;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.*;

/**
 * 功能：旧件出库
 *
 * @author BieBi
 * @create 2018-9-4 15:15:40
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = "war_used_deliver")
public class UsedDeliver extends Model {
    public static final String CONST_TABLE_NAME = "war_used_deliver";

    @Id
    @Column(name = "id", length = 16)
    @Comment("出库单号")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "编码",prefix = "CC%(company)%(yy)%(month)", padding = 5, useDateRange=true)
    private String id;  //出库单号

//    @Column(name = "source", length = 30, nullable = false)
//    @Comment("来源单号")
//    private String source;
//
//    @Column(name = "source_business_type", length = 32, nullable = false)
//    @Comment("来源单据类型")
//    private String sourceBusinessType;
//
//    @Column(name = "source_business_type_name", length = 64)
//    @Comment("来源单据类型名称")
//    private String sourceBusinessTypeName;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company; //公司编码

    @Comment("门店")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    private Dept dept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id", nullable = false)
    @Comment("仓库")
    private Location location;  // 仓库

    @Comment("总金额")
    @Column(name = "amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double totalAmount = 0; //总金额

    public void computeAmt() {
        // 赋予初始值
        totalAmount = 0;
        for (UsedDeliverItem item : usedDeliverItems) {
            item.computeAmt();
            totalAmount += item.getPriceTotal();
        }
    }


//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "customer_id", referencedColumnName = "id")
//    @Comment("客户")
//    private PartyRole customer; //客户
//
//
//    @Comment("车辆")
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "car_id", referencedColumnName = "id")
//    private CustomerCar car;
//
//
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "vip_id", referencedColumnName = "id")
//    @Comment("会员")
//    private PartyRole vip; //会员

//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "sale_id", referencedColumnName = "id")
//    @Comment("销售订单")
//    private RetailOrder sale;


    //    赠送原因(2：1-APP/微信下单救援；3: 2-非免费赠送, 0: 3-消费赠送, 4: 4-客诉赠送)
//    @States(name = "赠送原因", values = {
//            @State(id = "1", name = "APP/微信下单救援"),
//            @State(id = "2", name = "非免费赠送"),
//            @State(id = "3", name = "消费赠送"),
//            @State(id = "4", name = "客诉赠送")})
//    @JoinColumn(name = "give_reason", referencedColumnName = "id")
//    private BusinessAttributeValue giveReason;

//    旧件出库类型(0:标准销售出库;1:非标准出库;2:保险回收;3:政府回收;4:盘亏出库;5:非标准保险出库)
    /***
     * 0：写资金收入单，只能查询出具有价格的商品，出一般库存
     * 1：写资金收入单，只能查询出不具备价格的商品，出一般库存
     * 2：出保险库存
     * 3：出一般库存
     * 4：出一般库存
     */
    @States(name = "出库类型", values = {
            @State(id = "0", name = "标准销售出库"),
            @State(id = "1", name = "非标准出库"),
            @State(id = "2", name = "保险回收"),
            @State(id = "3", name = "政府回收"),
            @State(id = "4", name = "盘亏出库"),
    })
    @Comment("出库类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "used_deliver_type", nullable = false, referencedColumnName = "id")
    private BusinessAttributeValue usedDeliverType;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "money_income", referencedColumnName = "id")
    @Comment("资金收入单")
    private MoneyIncome moneyIncome;

    @Transient
    private String moneyIncomeId;

    public String getMoneyIncomeId() {
        if( moneyIncome == null ) return null;
        return moneyIncome.getId();
    }

    /***
     * 状态变化
     * 制单(回退) 审核 录入 收款 发货
     */
    @States(name = "订单状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "apply", name = "申请"),
            @State(id = "approve", name = "审核"),
            @State(id = "done", name = "完成"),
    })
    @Comment("状态")
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @Comment("变卖明细")
    @Column(name = "sell_detail", length = 4000)
    private String sellDetail;

    @Comment("备注")
    @Column(name = "remark", length = 4000)
    private String remark;  //备注

    @Comment("删除人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    private PartyRole deleteId;

    @Comment("删除日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    private Date deleteDate;

    @Comment("审核人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    private PartyRole approveId; // 审核人

    @Comment("审核日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "approve_date")
    private Date approveDate;    // 审核日期

    @Comment("申请人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "input_id", referencedColumnName = "id")
    private PartyRole inputId;

    @Comment("申请日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "input_date")
    private Date inputDate;

    @Comment("收款人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "receipt_id", referencedColumnName = "id")
    private PartyRole receiptId; // 收款人

    @Comment("收款日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "receipt_date")
    private Date receiptDate;    // 收款日期

    @Comment("发货人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "deliver_id", referencedColumnName = "id")
    private PartyRole deliverId; // 发货人

    @Comment("发货日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "deliver_date")
    private Date deliverDate;    // 发货日期

    @Comment("退回人")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "return_id", referencedColumnName = "id")
    private PartyRole returnId; // 退回人

    @Comment("退回日期")
    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "return_date")
    private Date returnDate;    // 退回日期

    @Comment("联系人")
    @Column(name = "contacts", length = 32)
    private String contacts;  //联系人

    @Comment("联系方式")
    @Column(name = "contacts_way", length = 32)
    private String contactsWay;  //联系方式

    @Comment("回收商")
    @Column(name = "recycler", length = 32)
    private String recycler;  //回收商

    @Comment("销售总金额")
    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double priceTotal = 0;//销售总金额
    /***
     * 功能：旧件入库单收款方式
     */
    @OneToMany(mappedBy = "usedDeliver", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<UsedDeliverIncomeType> usedDeliverIncomeTypes = new ArrayList<>();

    public List<UsedDeliverIncomeType> getUsedDeliverIncomeTypes() {
        if (usedDeliverIncomeTypes == null) return null;
        for (UsedDeliverIncomeType item : usedDeliverIncomeTypes) {
            item.setUsedDeliver(this);
        }
        return usedDeliverIncomeTypes;
    }


    /***
     * 功能： 旧件出库单明细
     */
    @OneToMany(mappedBy = "usedDeliver", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<UsedDeliverItem> usedDeliverItems = new HashSet();

    public Set<UsedDeliverItem> getUsedDeliverItems() {
        if (usedDeliverItems == null) return null;
        for (UsedDeliverItem item : usedDeliverItems) {
            item.setUsedDeliver(this);
        }
        return usedDeliverItems;
    }


    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }


    /***
     * 判断是否需要写入资金收入单
     */
    @Transient
    private boolean writeCapitalGain; // 写资金收入单标记

    public boolean getWriteCapitalGain() {
        switch (this.usedDeliverType.getId()) {
            case "UsedDeliver.usedDeliverType.0":
            case "UsedDeliver.usedDeliverType.1":
//            case "UsedDeliver.usedDeliverType.5":
                return true;
            case "UsedDeliver.usedDeliverType.2":
            case "UsedDeliver.usedDeliverType.3":
            case "UsedDeliver.usedDeliverType.4":
                return false;
            default:
                return false;
        }
    }

    /***
     * 判断出何种库存
     */
    @Transient
    private boolean deliverInsurance; // 出保险库存标记

    public boolean getDeliverInsurance() {
        switch (this.usedDeliverType.getId()) {
            case "UsedDeliver.usedDeliverType.0":
            case "UsedDeliver.usedDeliverType.1":
            case "UsedDeliver.usedDeliverType.3":
            case "UsedDeliver.usedDeliverType.4":
                return false;
            case "UsedDeliver.usedDeliverType.2":
            case "UsedDeliver.usedDeliverType.5":
                return true;
            default:
                return false;
        }
    }

    /***
     * 判断取价格标记
     */
    @Transient
    private boolean priceProcedure; // 定价过程标记

    public boolean getPriceProcedure() {
        switch (this.usedDeliverType.getId()) {
            case "UsedDeliver.usedDeliverType.0":
                return true;
            default:
                return false;
        }
    }

}
